package com.lanhai.zhonglai.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import com.lanhai.zhonglai.beans.AgvBean;
import com.lanhai.zhonglai.beans.StationBean;
import com.lanhai.zhonglai.dao.AgvTransferLog;
import com.lanhai.zhonglai.dao.TransLogDao;
import com.lanhai.zhonglai.enums.AgvReceiveEnum;
import com.lanhai.zhonglai.enums.TransDirectionEnum; 
import com.lanhai.zhonglai.interfaces.ICmdLog;
import com.lanhai.zhonglai.mapper.TransLogMapper;


/**
 * 日志记录,暂时以写文件为主
 *
 * @author zhengwei
 */
@EnableAsync
@Service
public class CmdLogImpl implements ICmdLog {
 
	
    @Autowired
    TransLogMapper tLogMapper;

    private static final Logger agvlog = LogManager.getLogger("agvlog");
    private static final Logger stationlog = LogManager.getLogger("station");

    static Map<Integer, String> agvReceiveMap= new ConcurrentHashMap<Integer, String>(); 
    static Map<String, String> savelogMap =new ConcurrentHashMap<String, String>(); 

    


    //写文件

    @Override
    public synchronized void addAgvSendLog(int agvid, String remark, String dataStr) {


        String log = String.format("AGV:【%d】，发送消息:%s，消息内容:【%s】", agvid, remark, dataStr);
        agvlog.info(log);
    }

    @Override
    public synchronized void addAgvReceiveLog(int agvid, String remark, String dataStr) {
        //过滤相同的指令，只是不做记录，不影响处理
        String last = agvReceiveMap.get(agvid);
        if (last != null && last.equals(dataStr)) {
           return;
        }
        agvReceiveMap.put(agvid, dataStr);


        String log = String.format("收到来自AGV:【%d】的消息:【%s】，消息内容:【%s】", agvid, remark, dataStr);
        agvlog.info(log);
    }

    @Override
    public synchronized void addStationSendLog(String ip, int port, int line, String remark, String dataStr, String stationname) {


        String log = String.format("对接设备IP:【%s】,线别:【%d】，发送消息:%s，消息内容:【%s】", stationname, line, remark, dataStr);
        stationlog.info(log);
    }

    @Override
    public synchronized void addStationReceiveLog(String ip, int line, String remark, String dataStr, String stationname) {

        String log = String.format("收到对接设备IP:【%s】,线别:【%d】的消息:【%s】，消息内容:【%s】", stationname, line, remark, dataStr);
        stationlog.info(log);
    }
 
    @Async("agvExecutor")
    @Override
    public void saveTransLog(int agvid, int dotno, StationBean station,TransDirectionEnum transType) {
    	 
    
    	 long t=System.currentTimeMillis();
        TransLogDao lg = new TransLogDao();
        Calendar c = Calendar.getInstance(Locale.CHINA);
        lg.setAgvid(agvid);
        lg.setDotno(dotno);
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int min = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        lg.setDays(year * 10000 + month * 100 + day);

        lg.setHours(hour * 100 + min);
        lg.setSpecialline(station.getSpecialline());
        lg.setTime(t);
        // 算班次
        if (lg.getHours() < 800) {
            c.add(Calendar.DAY_OF_MONTH, -1);
            // 夜班算前一天的
            lg.setDutyday(
                    c.get(Calendar.YEAR) * 10000 + (c.get(Calendar.MONTH) + 1) * 100 + c.get(Calendar.DAY_OF_MONTH));
        } else {
            lg.setDuty(lg.getDays());
            if (lg.getHours() <= 2000) {
                // 白班 0730-1930
                lg.setDuty(1);
            } else {
                // 夜班
                lg.setDuty(0);
            }
        }
       

        String time = String.format("%d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, min, second);
        tLogMapper.addLog(lg);
        
        
        if(transType!=TransDirectionEnum.Both) {
        	  AgvTransferLog zyobj = new AgvTransferLog(agvid, station.getProcess(), station.getIp(), station.getStationname(), time,transType);
        	  tLogMapper.addTransferLog(zyobj);
        }else {
        	//双层，进出都要写
        	List<AgvTransferLog> transList=new ArrayList<AgvTransferLog>();
        	  AgvTransferLog zyobjIn = new AgvTransferLog(agvid, station.getProcess(), station.getIp(), station.getStationname(), time,TransDirectionEnum.OnlyIn);
        	  transList.add(zyobjIn); 
        	  AgvTransferLog zyobjOut = new AgvTransferLog(agvid, station.getProcess(), station.getIp(), station.getStationname(), time,TransDirectionEnum.OnlyOut);
        	  transList.add(zyobjOut); 
        	  tLogMapper.addTransferLogList(transList);
        } 

    }

    @Async("agvExecutor")
	@Override
	public void saveTransLogOnce(AgvBean agv, StationBean station , TransDirectionEnum transType,
			AgvReceiveEnum receiveType) {
		if(agv==null||station==null) {
			 agvlog.info("agv is null or station is null");
			return;
		}
		
		String key=String.format("%d", agv.getAgvId() );  //AGVID 
		String value=String.format("%d_%s", station.getDotno(),  receiveType.getName());  //点位+传入或者传出
		
		String ole=savelogMap.get(key);
		if(ole!=null && ole.equals(value)) {
			//和上一次的传输状态相同，不记录
			return;
		}
		savelogMap.put(key, value);
		saveToDB(agv,station,transType);
	}

	
	
	void saveToDB(AgvBean agv, StationBean station , TransDirectionEnum transType)  {

	   	   long t=System.currentTimeMillis();
	       TransLogDao lg = new TransLogDao();
	       Calendar c = Calendar.getInstance(Locale.CHINA);
	       lg.setAgvid(agv.getAgvId());
	       lg.setDotno(station.getDotno());
	       int year = c.get(Calendar.YEAR);
	       int month = c.get(Calendar.MONTH) + 1;
	       int day = c.get(Calendar.DAY_OF_MONTH);
	       int hour = c.get(Calendar.HOUR_OF_DAY);
	       int min = c.get(Calendar.MINUTE);
	       int second = c.get(Calendar.SECOND);
	       lg.setDays(year * 10000 + month * 100 + day);

	       lg.setHours(hour * 100 + min);
	       lg.setSpecialline(station.getSpecialline());
	       lg.setTime(t);
	       // 算班次
	       if (lg.getHours() < 800) {
	           c.add(Calendar.DAY_OF_MONTH, -1);
	           // 夜班算前一天的
	           lg.setDutyday(
	                   c.get(Calendar.YEAR) * 10000 + (c.get(Calendar.MONTH) + 1) * 100 + c.get(Calendar.DAY_OF_MONTH));
	       } else {
	           lg.setDuty(lg.getDays());
	           if (lg.getHours() <= 2000) {
	               // 白班 0730-1930
	               lg.setDuty(1);
	           } else {
	               // 夜班
	               lg.setDuty(0);
	           }
	       }
	      

	       String time = String.format("%d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, min, second); 
	       tLogMapper.addLog(lg);
	       
	       
			if (transType != TransDirectionEnum.Both) {
				AgvTransferLog zyobj = new AgvTransferLog(agv.getAgvId(), station.getProcess(), station.getIp(),
						station.getStationname(), time, transType);
				tLogMapper.addTransferLog(zyobj);
			} else {
				// 双层，进出都要写
				List<AgvTransferLog> transList = new ArrayList<AgvTransferLog>();
				AgvTransferLog zyobjIn = new AgvTransferLog(agv.getAgvId(), station.getProcess(), station.getIp(),
						station.getStationname(), time, TransDirectionEnum.OnlyIn);
				transList.add(zyobjIn);
				AgvTransferLog zyobjOut = new AgvTransferLog(agv.getAgvId(), station.getProcess(), station.getIp(),
						station.getStationname(), time, TransDirectionEnum.OnlyOut);
				transList.add(zyobjOut);
				tLogMapper.addTransferLogList(transList);
			}
			
	}

}
